package com.bestv.xml.parser;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Henry on 14-7-9.
 */
public abstract class Parser {
    private Logger logger = LoggerFactory.getLogger(getClass());

    protected String xpathExpression;

    protected Map<String, String> toMap(File file) {
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(file);
        } catch (DocumentException e) {
            logger.error("Error on read file.", e);
        }

        Element root = (Element) document.selectSingleNode(xpathExpression);
        if (root == null) return null;

        Map<String, String> map = new HashMap<String, String>();
        List<Attribute> attributes = root.attributes();
        for (Attribute attribute : attributes) {
            String key = attribute.getName();
            String val = attribute.getValue();
            map.put(key, val);
        }
        List<Element> elements = root.elements();
        for (Element element : elements) {
            String key = element.attribute("Name").getValue();
            String val = element.getText();
            map.put(key, val);
        }
        return map;
    }
}
